<template>
	<view class="chat-detail" :style="{'--height':`${chatWindowHeight}rpx`,'--duration':`.${keybordDuration}s`}">
		<common-navbar :titleSize="24" :title="sessionInfo?sessionInfo.sessionName:'聊天详情'" />
		<view class="chat-detail-main">
			<orderStatusBar v-if="orderDetail" :orderDetail="orderDetail"
				@complateQuicklyConsult="complateQuicklyConsult" />
			<scroll-view class="chat-window" scroll-y @scrolltoupper="scrolltoupper"
				@click.capture="closePublishMessageBox" scroll-anchoring
				:scroll-into-view="`messageItem${scrollCurrentId}`">
				<problemDescription :orderDetail="orderDetail" v-if="orderDetail" />
				<view v-for="(item,index) in messageList" :key="item.id" :id="`messageItem${item.id}`"
					class="messageitem">
					<messageItem :messageInfo="item" :isShowDate="isShowDate(item, messageList[index - 1])"
						@imgMsgLoadSuccess="isFirstLoad?scrollBottom():{}" ref="messageItem"
						@allVoiceStopPlay="allVoiceStopPlay" @setMsgType="setMsgType"
						@keyboardheightchange="keyboardheightchange" @submitEvaluation="submitEvaluation"
						@showMsgMenu="showMsgMenu" :currentLongpressMsgId="currentLongpressMsgId"
						@withdrawMsg="withdrawMsg" @toEvaluation="toEvaluation" :orderDetail="orderDetail" :consultDetail="consultDetail"/>
				</view>
				<vipModule v-if="isNoConsultDuration" />
				<u-mask :show="isScrollViewLoadingMaskShow">
					<u-loading size="100" color="#0e87f2" />
				</u-mask>
			</scroll-view>
			<messageEmitter @keyboardheightchange="keyboardheightchange" @setMsgType="setMsgType" :msgType="msgType"
				@submitTextMessage="submitTextMessage" @showContactList="showContactList"
				@sendVoiceMsg="sendVoiceMsg($event)" :isNoConsultDuration="isNoConsultDuration"
				:orderDetail="orderDetail" />
		</view>
		<selectMsgtypeMenu :msgType="msgType" @sendImageMessage="sendImageMessage($event)"
			@sendLocationMsg="sendLocationMsg($event)" @sendVideoFileMsg="sendVideoFileMsg($event)"
			@sendFileMsg="sendFileMsg($event)" @uploadFile="onUploadFile" @uploadFileEnd="onUploadFileEnd" />
		<vipPromote ref="vipPromote" />
		<contactList :isContactListShow.sync="isContactListShow" :sessionInfo="sessionInfo" :memberList="memberList" />
	</view>
</template>

<script>
	let scrollBottomTimer;
	import messageEmitter from "./components/message-emitter/messageEmitter.vue";
	import selectMsgtypeMenu from "./components/select-msgtype-menu/selectMsgtypeMenu.vue";
	import messageItem from "./components/message-item/messageItem.vue";
	import vipPromote from "./components/vip-promote/vipPromote.vue";
	import contactList from "./components/contact-list/contactList.vue";
	import problemDescription from "./components/problem-description/problemDescription.vue";
	import orderStatusBar from "./components/order-status-bar/orderStatusBar.vue";
	import serviceEvaluation from "./components/service-evaluation/serviceEvaluation.vue";
	import vipModule from "./components/vip-module/vipModule.vue";

	export default {
		options: {
			styleIsolation: 'shared'
		},
		data() {
			return {
				keyboardHeight: 0,
				keybordDuration: 0,
				msgType: 'text',
				sessionInfo: null,
				isGetHistoryMessageLoadingShow: false,
				messageList: [],
				isFirstLoad: true,
				currentMsgId: '',
				scrollCurrentId: '',
				isMessageMenuShow: false,
				isScrollViewLoadingMaskShow: false,
				memberList: [],
				isContactListShow: false,
				currentLongpressMsgId: '',
				orderDetail: null,
				consultDetail: null,
				isNoConsultDuration: false,
				taskCode: undefined,
			}
		},
		async onLoad(option) {
			await this.$websocketStatus;
			this.sessionInfo = JSON.parse(decodeURIComponent(decodeURIComponent(option.sessionInfo)));
			if (this.sessionInfo.chatType == 'groupChat') {
				//获取群成员列表
				const err = await this.getGroupMembers();
				//获取不到群，咨询结束
				if (err && err.info.split(':')[1] == 'do not find this group') {
					uni.showModal({
						title: '提示',
						content: '本次咨询已结束',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack()
							} else if (res.cancel) {}
						}
					});
				} else {
					const {
						data
					} = await this.$u.post(this.$restUrl.getConsultTypeIfByGroupId, {
						groupid: this.sessionInfo.sessionId
					})
					if (data && data.type == 1) {
						this.consultDetail = data;
						console.log('this.consultDetail>>>>>>>>>>>>>>>>>>>>>>>>>>>>>',this.consultDetail)
					}
					const res = await this.$u.post(this.$restUrl.getTaskCodeByGroupId, {
						groupid: this.sessionInfo.sessionId
					})
					if (res.data.task_code) {
						this.taskCode = res.data.task_code;
						const result = await this.$u.post(this.$restUrl.getOrderDetailByTaskcode, {
							task_code: this.taskCode
						})
						if (!(result.data instanceof Array)) {
							this.orderDetail = result.data;
							const {avatars,lawyer_name} = (await this.$u.post(this.$restUrl.lawyerInfoByTaskCode, {
				            task_code: this.taskCode
			                })).data
							this.$set(this.orderDetail,'lawyer_name',lawyer_name);
							this.$set(this.orderDetail,'lawyer_avatar',avatars);
						}
						console.log('this.orderDetail>>>>>>>>>>>>>>>>>>>>>>>>', result);
					}

					this.$u.post(this.$restUrl.removeGroupAtList, {
						groupid: this.sessionInfo.sessionId
					})
				}
			}
			uni.IM.setSessionRead(this.sessionInfo.sessionId, this.sessionInfo.chatType);
			this.fetchHistoryMessages();
			uni.onKeyboardHeightChange(res => {
				console.log(res.height)
				this.keyboardHeight = res.height;
				this.scrollBottom();
			})
		},
		mounted() {
			uni.$off('onMessage');
			uni.$on('onMessage', msg => {
				this.onMsgHandler(msg);
			})

			uni.$off('onWithdrawMsg');
			uni.$on('onWithdrawMsg', msg => {
				this.onWithdrawMsgHandler(msg);
			})
		},
		onUnload() {
			this.$store.commit('$setCurrentSessionId', undefined);
		},
		watch: {
			sessionInfo() {
				this.$u.vuex('currentSessionId', this.sessionInfo.sessionId);
			}
		},
		components: {
			messageEmitter,
			selectMsgtypeMenu,
			messageItem,
			vipPromote,
			contactList,
			problemDescription,
			orderStatusBar,
			serviceEvaluation,
			vipModule
		},
		computed: {
			chatWindowHeight() {
				//当前选中的消息类型为文本类型或者音频类型时
				if (this.msgType == 'text' || this.msgType == 'voice') {
					//如果软键盘高度大于0也就是软键盘开启状态下
					if (this.keyboardHeight > 0) {
						//uniapp设计尺寸750*(状态栏高度+navbar高度+软键盘高度-底部安全区高度）/手机宽度像素
						// return 750 * (this.$systemInfo.statusBarHeight + 44 + this.keyboardHeight - this.$systemInfo
						// 	.safeAreaInsets
						// 	.bottom) / this.$systemInfo.screenWidth;
						return 750 * (this.$systemInfo.statusBarHeight + 44 + this.keyboardHeight) / this.$systemInfo
							.screenWidth;
					} else {
						//软键盘关闭状态下不减去底部安全区高度
						return 750 * (this.$systemInfo.statusBarHeight + 44 + this.keyboardHeight) / this.$systemInfo
							.screenWidth;
					}
				} else {
					//当前打开了表情菜单获取其他消息类型菜单，不计算软键盘的高度
					return (750 * (this.$systemInfo.statusBarHeight + 44) / this.$systemInfo
						.screenWidth) + this.messageMenuHeight;
				}
			},
			messageMenuHeight() {
				if (this.msgType == 'text' || this.msgType == 'voice') {
					return 0
				} else if (this.msgType == 'emoji') {
					return 300
				} else if (this.msgType == 'other') {
					return 228
				}
			},
		},
		methods: {
			toEvaluation(e) {
				this.$u.route(
					`/pages_lawyer/lawyer_evaluation/lawyerEvaluation?taskCode=${e.taskCode}&evaluateId=${e.evaluateId}`
					)
			},
			showMsgMenu(e) {
				console.log(e)
				this.currentLongpressMsgId = e;
			},
			keyboardheightchange(e) {
				// this.keyboardHeight = e.height;
				// console.log(this.keyboardHeight)
				// this.keybordDuration = e.duration*100;
				// console.log(this.keybordDuration)
			},
			setMsgType(e) {
				console.log(e);
				this.msgType = e;
				console.log(this.messageMenuHeight)
			},
			scrolltoupper() {
				this.fetchHistoryMessages();
			},
			async fetchHistoryMessages() {
				console.log('sessionId>>>>>>>>>>>>>>>>>>>>', this.sessionInfo.sessionId);
				if (this.isGetHistoryMessageLoadingShow) return
				// if(this.sessionInfo.taskCode){
				// 	this.orderDetail = (await this.$u.post(this.$restUrl.getOrderDetailQuickly,{task_code:this.sessionInfo.taskCode})).data;
				// 	console.log(this.orderDetail)
				// }
				this.isGetHistoryMessageLoadingShow = true;
				this.isScrollViewLoadingMaskShow = true;
				let options = {
					sessionId: this.sessionInfo.sessionId,
					messageCount: 20,
					isGroup: this.sessionInfo.chatType == "groupChat",
					start: this.messageList[0],
				}
				uni.IM.fetchHistoryMessages(options)
					.then(res => {
						//重置拉取历史消息的游标
						uni.IM.msgCache();
						this.isGetHistoryMessageLoadingShow = false;
						//设置获取历史列表之前的最上面一条的历史消息ID，用于滚动到对应的位置
						let oldFirstMessageElementId = this.messageList[0] ?
							this.messageList[0].id :
							undefined;
						//将获取到的历史消息放入历史消息列表中
						this.messageList.unshift(...res);
						if (oldFirstMessageElementId && res.length > 0) {
							this.isFirstLoad = false;
							this.scrollToByElementId(oldFirstMessageElementId);
						} else if (!oldFirstMessageElementId&&res.length>6) {
							this.scrollBottom();
							this.isScrollViewLoadingMaskShow = false;
						} else {
							this.isScrollViewLoadingMaskShow = false;
						}
						//客服自动回复
						// let dayStartTime = new Date(new Date().toLocaleDateString()).getTime(); // 当天0点的时间戳
						// if (this.sessionInfo.consultId && (!this.messageList.length || this.messageList[this
						// 			.messageList.length - 1].time <
						// 		dayStartTime)) {
						// 	this.$u.post(this.$restUrl.autoReply, {
						// 		sender_phone: this.sessionInfo.sessionId,
						// 		consult_type_id: this.sessionInfo.consultId,
						// 	})
						// }
					}).catch(err => {
						this.isGetHistoryMessageLoadingShow = false;
						this.isScrollViewLoadingMaskShow = false;
					})
			},
			scrollToByElementId(id) {
				// this.scrollCurrentId = '';
				clearTimeout(scrollBottomTimer)
				scrollBottomTimer = setTimeout(() => {
					this.scrollCurrentId = id;
					this.isScrollViewLoadingMaskShow = false;
				}, 200)
			},
			scrollBottom() {
				if (this.messageList.length == 0) {
					return
				}
				clearTimeout(scrollBottomTimer)
				this.scrollCurrentId = '';
				scrollBottomTimer = setTimeout(() => {
					this.$nextTick(() => {
						console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
						this.scrollCurrentId = this.messageList[this.messageList.length - 1].id;
						this.isScrollViewLoadingMaskShow = false;
					})
				}, 400)
			},
			isShowDate(currentMessageItem, prevMessageItem) {
				if (!prevMessageItem) {
					return true;
				} else if (currentMessageItem.time - prevMessageItem.time >= 300000) {
					return true;
				} else {
					return false;
				}
			},
			closePublishMessageBox() {
				this.msgType = this.msgType == 'voice' ? 'voice' : 'text';
				this.isMessageMenuShow = false;
				this.currentLongpressMsgId = '';
			},
			async getGroupMembers() {
				try {
					const res = await this.$u.post(this.$restUrl.getGroupMember, {
						groupid: [this.sessionInfo.sessionId]
					})
					this.memberList = res.data[0].affiliations;
					this.memberList.unshift({
						nickname: res.data[0].nickname,
						avatars: res.data[0].avatars,
						uuid: res.data[0].uuid,
						member: res.data[0].owner,
						role: res.data[0].role
					})
				} catch (err) {
					return err
				}
			},
			getMentionList(textMsgContent) {
				let mentionList = [];
				if (this.sessionInfo.chatType == 'groupChat') {
					if (textMsgContent.indexOf('@所有人 ') != -1) {
						mentionList = this.memberList.map(item => item.member);
						return mentionList.filter(item => item != uni.IM.userId);
					} else {
						this.memberList.forEach(item => {
							if (this.$utils.isMentionMember(item.nickname, textMsgContent)) {
								mentionList.push(item.member);
							}
						})
						return mentionList.filter(item => item != uni.IM.userId);
					}
				} else {
					return mentionList
				}
			},
			showContactList() {
				if (this.sessionInfo.chatType != 'groupChat') {
					return
				}
				this.isContactListShow = true;
			},
			async onMsgHandler(msg) {
				if (this.sessionInfo.chatType == 'groupChat' && this.sessionInfo.sessionId != msg.to) {
					return
				} else if (this.sessionInfo.chatType == 'singleChat' && this.sessionInfo.sessionId != msg.from) {
					return
				}
				this.messageList.push(msg);
				uni.IM.setSessionRead(this.sessionInfo.sessionId, this.sessionInfo.chatType);
				this.scrollBottom();
				if (msg.ext.messageType == 'service_evaluation') {
					const result = await this.$u.post(this.$restUrl.getOrderDetailByTaskcode, {
						task_code: this.taskCode
					})
					this.orderDetail = result.data;
				}
			},
			onWithdrawMsgHandler(msg) {
				this.messageList.forEach((item, index) => {
					if (item.id == msg.mid) {
						this.messageList.splice(index, 1);
					}
				})
			},
			sendIMPush(msg, content, mentionList = []) {
				if (msg.type.toLowerCase() == 'groupchat') {
					//群聊
					const options = {
						groupid: this.sessionInfo.sessionId,
						content: content.substr(0, 30),
						at_customer: mentionList,
					}
					this.$u.post(this.$restUrl.IMGroupPush, options);
				} else {
					//单聊
					const options = {
						to_customer: this.sessionInfo.sessionId,
						content,
					}
					this.$u.post(this.$restUrl.IMSinglePush, options);
				}
			},
			allVoiceStopPlay() {
				this.messageList.forEach((item, index) => {
					this.$refs.messageItem[index].stopPlayVideo();
				})
			},
			async submitTextMessage(textValue, payload) {
				const mention_list = this.getMentionList(textValue)
				const textMsgPayload = {
					userName: this.userInfo.nickname ? this.userInfo.nickname : '',
					userAvatar: this.userInfo.avatars ? this.userInfo.avatars : '',
					messageType: "text",
					mentionList: mention_list,
					...payload,
				}
				const options = {
					textValue,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: textMsgPayload
				}
				uni.IM.sendTextMsg(options).then(res => {
					this.messageList.push(res);
					uni.$emit('sessionListOnMessage', res);
					this.scrollBottom();
					this.sendIMPush(res, textValue, mention_list);
				}).catch(err => {
					this.messageList.push(err);
					uni.$emit('sessionListOnMessage', err);
					this.scrollBottom();
				})
			},
			async sendImageMessage(imagePaths, payload) {
				const imageMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "image",
					...payload,
				}

				for (let item of imagePaths) {
					const options = {
						filePath: item,
						receiverId: this.sessionInfo.sessionId,
						chatType: this.sessionInfo.chatType,
						payload: imageMsgPayload
					}
					uni.IM.sendImageMsg(options).then(res => {
						this.messageList.push(res);
						uni.$emit('sessionListOnMessage', res);
						this.scrollBottom();
						this.sendIMPush(res, '[图片]');
					}).catch(err => {
						this.messageList.push(err);
						uni.$emit('sessionListOnMessage', err);
						this.scrollBottom();
					})
				}
			},
			async sendLocationMsg(locationInfo, payload) {
				const locationMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "location",
					...payload,
				}
				uni.IM.sendLocationMsg({
					locationInfo,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: locationMsgPayload,
				}).then(res => {
					this.messageList.push(res);
					uni.$emit('sessionListOnMessage', res);
					this.scrollBottom();
					this.sendIMPush(res, '[定位]');
				}).catch(err => {
					this.messageList.push(err);
					uni.$emit('sessionListOnMessage', err);
					this.scrollBottom();
				})
			},
			async sendVideoFileMsg(videoInfo, payload) {
				const videoMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "video",
					...payload,
				}
				const options = {
					videoInfo,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: videoMsgPayload,
				}
				uni.IM.sendVideoMsg(options).then(res => {
					this.messageList.push(res);
					uni.$emit('sessionListOnMessage', res);
					this.scrollBottom();
					this.sendIMPush(res, '[视频]');
				}).catch(err => {
					this.messageList.push(err);
					uni.$emit('sessionListOnMessage', err);
					this.scrollBottom();
				})
			},
			async sendFileMsg(fileInfo, payload) {
				const fileMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "file",
					fileLength: fileInfo.size,
					...payload,
				}
				uni.IM.sendFileMessage({
					fileInfo,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: fileMsgPayload,
				}).then(res => {
					this.messageList.push(res);
					uni.$emit('sessionListOnMessage', res);
					this.scrollBottom();
					this.sendIMPush(res, '[文件]');
				}).catch(err => {
					this.messageList.push(err);
					uni.$emit('sessionListOnMessage', err);
					this.scrollBottom();
				})
			},
			async sendVoiceMsg({
				filePath,
				duration
			}, payload) {
				const voicewMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "voice",
					...payload,
				}
				const options = {
					filePath,
					duration,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: voicewMsgPayload,
				}
				uni.IM.sendVoiceMsg(options).then(res => {
					this.messageList.push(res);
					uni.$emit('sessionListOnMessage', res);
					this.scrollBottom();
					this.sendIMPush(res, '[语音]');
				}).catch(err => {
					this.messageList.push(err);
					uni.$emit('sessionListOnMessage', err);
					this.scrollBottom();
				})
			},
			async withdrawMsg(msg, payload) {
				const withdrawMsgPayload = {
					userName: this.userInfo.nickname,
					userAvatar: this.userInfo.avatars,
					messageType: "withdraw",
					...payload,
				}
				const options = {
					id: msg.mid ? msg.mid : msg.id,
					receiverId: this.sessionInfo.sessionId,
					chatType: this.sessionInfo.chatType,
					payload: withdrawMsgPayload,
				}
				await uni.IM.withdrawMsg(options);
				this.$showToast('已撤回信息');
				this.messageList.splice(this.messageList.indexOf(msg), 1);
				const callbackMsg = await uni.IM.sendWithdrawCallbackMsg(options);
				this.messageList.push(callbackMsg);
				uni.$emit('sessionListOnMessage', callbackMsg);
				this.scrollBottom();
				this.sendIMPush(msg, `${this.userInfo.nickname}撤回了一条消息`);
			},
			async complateQuicklyConsult() {
				await this.$u.post(this.$restUrl.complateQuicklyConsult, {
					task_code: this.taskCode
				});
				const result = await this.$u.post(this.$restUrl.getOrderDetailByTaskcode, {
					task_code: this.taskCode
				})
				this.orderDetail = result.data;
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "./chatDetail.scss";
</style>
